package com.lepu.app.fun.tool.jqtx;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.ArrayWheelAdapter;
import com.core.lib.ui.wheel.NumericWheelAdapter;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.DateType;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.tool.jqtx.bean.BeanJqtx;
import com.lepu.app.fun.tool.jqtx.util.ToolJqtxUtil;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class JqtxMainActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest {

	private static final String REQUEST_FINISH = "request_finish";

	int mMenstrualPeriod = 5;// 月经天数
	int mMenstrualCycle = 28;// 月经周期
	String mLastMenstruationDate = "";
	int mIsAlert = 1;// 是否提醒
	Map<String, Integer> mAlertTypeMaps = new HashMap<String, Integer>();// 提醒类型
	int mAlertBeforeDay = 1;// 提醒提前天数
	String mAlertTime = "08:00:00";// 提醒时间

	Button mYesButton;
	Button mNoButton;

	String[] mRemindArray = null;
	BeanJqtx mTempBeanJqtx = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedStatusBar = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jqtx_main_activity);

		UtilityBase.setStatusBarRes(this, R.color.color_jqtx, true);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("经期提醒");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setTopbarBackground(R.color.color_jqtx);

		TextView beginTimeValueTextView = (TextView) findViewById(R.id.beginTimeValueTextView);
		mLastMenstruationDate = DateUtilBase.stringFromDate(new Date(),
				DateUtilBase.YEAR_MONTH_DAY);
		beginTimeValueTextView.setText(mLastMenstruationDate);

		mYesButton = (Button) findViewById(R.id.yesButton);
		mNoButton = (Button) findViewById(R.id.noButton);

		mYesButton.setSelected(true);

		mRemindArray = getResources().getStringArray(R.array.array_jqtx_date);

		boolean flag = getIntent().getBooleanExtra("IsModify", false);
		if (flag) {
			BeanJqtx item = ToolJqtxUtil.getInstance(this).getJqtx();
			initData(item);
		}
	}

	private void initData(BeanJqtx item) {
		if (item != null && item.MenstrualPeriod > 0) {
			TextView jqValueTextView = (TextView) findViewById(R.id.jqValueTextView);
			TextView zqValueTextView = (TextView) findViewById(R.id.zqValueTextView);
			TextView beginTimeValueTextView = (TextView) findViewById(R.id.beginTimeValueTextView);
			TextView txTimeValueTextView = (TextView) findViewById(R.id.txTimeValueTextView);

			mMenstrualPeriod = item.MenstrualPeriod;
			mMenstrualCycle = item.MenstrualCycle;
			mLastMenstruationDate = item.LastMenstruationDate;
			jqValueTextView.setText(String.valueOf(item.MenstrualPeriod));
			zqValueTextView.setText(String.valueOf(item.MenstrualCycle));
			beginTimeValueTextView.setText(String
					.valueOf(mLastMenstruationDate));

			if (item.AlertBeforeDay > 0) {
				mAlertBeforeDay = item.AlertBeforeDay;
				mAlertTime = item.AlertTime;

				String remindBefore = mRemindArray[item.AlertBeforeDay - 1];
				StringBuffer alertTime = new StringBuffer(item.AlertTime);
				alertTime = alertTime.deleteCharAt(alertTime.length() - 1);
				alertTime = alertTime.deleteCharAt(alertTime.length() - 1);
				alertTime = alertTime.deleteCharAt(alertTime.length() - 1);

				txTimeValueTextView.setText(remindBefore + "	"
						+ alertTime.toString());
			}

			mIsAlert = item.IsAlert;
			if (item.IsAlert == 1) {
				viewClick(mYesButton);
			} else {
				viewClick(mNoButton);
			}

			if (!TextUtils.isEmpty(item.AlertType)) {
				String[] alertTypeArray = item.AlertType.split("|");
				if (alertTypeArray.length > 0) {
					for (int i = 0; i < alertTypeArray.length; i++) {
						int type = UtilityBase.parseInt(alertTypeArray[i]);
						if (type == 1) {
							Button yjqButton = (Button) findViewById(R.id.yjqButton);
							yjqButton.setSelected(true);

							mAlertTypeMaps.put("yjq", 1);
						} else if (type == 2) {
							Button aqqButton = (Button) findViewById(R.id.aqqButton);
							aqqButton.setSelected(true);

							mAlertTypeMaps.put("aqq", 2);
						} else if (type == 3) {
							Button yyqButton = (Button) findViewById(R.id.yyqButton);
							yyqButton.setSelected(true);

							mAlertTypeMaps.put("yyq", 3);
						} else if (type == 4) {
							Button plqButton = (Button) findViewById(R.id.plqButton);
							plqButton.setSelected(true);

							mAlertTypeMaps.put("plq", 4);
						}
					}
				}
			}
			
			//
		}
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.jqValueTextView:

			showJqValue();
			break;
		case R.id.zqValueTextView:

			showZqValue();
			break;
		case R.id.beginTimeValueTextView:

			showBeginTimeValue();
			break;
		case R.id.yesButton:
		case R.id.noButton:

			TextView txTimeValueTextView = (TextView) findViewById(R.id.txTimeValueTextView);
			Button yjqButton = (Button) findViewById(R.id.yjqButton);
			Button aqqButton = (Button) findViewById(R.id.aqqButton);
			Button yyqButton = (Button) findViewById(R.id.yyqButton);
			Button plqButton = (Button) findViewById(R.id.plqButton);

			boolean enabled = false;
			if (rid == R.id.yesButton) {
				mNoButton.setSelected(false);
				mYesButton.setSelected(true);

				mIsAlert = 1;

				enabled = true;
				txTimeValueTextView.setTextColor(getResources().getColor(
						R.color.color_black));
			} else {
				mNoButton.setSelected(true);
				mYesButton.setSelected(false);

				mIsAlert = 0;

				enabled = false;
				txTimeValueTextView.setTextColor(getResources().getColor(
						R.color.color_text_light_gray));
				
				yjqButton.setSelected(false);
				aqqButton.setSelected(false);
				yyqButton.setSelected(false);
				plqButton.setSelected(false);
				
				mAlertTypeMaps.clear();
			}

			txTimeValueTextView.setEnabled(enabled);

			yjqButton.setEnabled(enabled);
			aqqButton.setEnabled(enabled);
			yyqButton.setEnabled(enabled);
			plqButton.setEnabled(enabled);
			
			break;
		case R.id.yjqButton:

			view.setSelected(!view.isSelected());
			if (view.isSelected()) {
				mAlertTypeMaps.put("yjq", 1);
			} else {
				mAlertTypeMaps.remove("yjq");
			}

			break;
		case R.id.aqqButton:

			view.setSelected(!view.isSelected());
			if (view.isSelected()) {
				mAlertTypeMaps.put("aqq", 2);
			} else {
				mAlertTypeMaps.remove("aqq");
			}
			break;
		case R.id.yyqButton:

			view.setSelected(!view.isSelected());
			if (view.isSelected()) {
				mAlertTypeMaps.put("yyq", 3);
			} else {
				mAlertTypeMaps.remove("yyq");
			}
			break;
		case R.id.plqButton:

			view.setSelected(!view.isSelected());
			if (view.isSelected()) {
				mAlertTypeMaps.put("plq", 4);
			} else {
				mAlertTypeMaps.remove("plq");
			}
			break;
		case R.id.txTimeValueTextView:

			showTxTimeValue();
			break;
		case R.id.finishButton:

			submit();
			break;

		default:
			break;
		}
	}

	/**
	 * 选择经期
	 */
	private void showJqValue() {
		final ArrayList<Integer> dataArraylist = new ArrayList<Integer>();
		for (int i = 1; i <= 10; i++) {
			dataArraylist.add(i);
		}

		final String[] array = new String[dataArraylist.size()];
		int currentIndex = mMenstrualPeriod-1;

		for (int i = 0; i < dataArraylist.size(); i++) {
			array[i] = String.format("经期%d天", dataArraylist.get(i));
		}

		final MyDialog dialog = new MyDialog(this);
		dialog.setSimpleSelectPicker(array, currentIndex)
				.setTitle("请选择经期")
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						WheelView wv_content = (WheelView) v
								.findViewById(R.id.simpleSelectPicker);
						int index = wv_content.getCurrentItem();

						TextView jqValueTextView = (TextView) findViewById(R.id.jqValueTextView);
						jqValueTextView.setText(String.valueOf(dataArraylist
								.get(index)));

						mMenstrualPeriod = dataArraylist.get(index);

					}
				}).create(null).show();
	}

	/**
	 * 选择周期
	 */
	private void showZqValue() {
		final ArrayList<Integer> dataArraylist = new ArrayList<Integer>();
		for (int i = 20; i <= 50; i++) {
			dataArraylist.add(i);
		}

		final String[] array = new String[dataArraylist.size()];
		int currentIndex = mMenstrualCycle-20;

		for (int i = 0; i < dataArraylist.size(); i++) {
			array[i] = String.format("周期%d天", dataArraylist.get(i));
		}

		final MyDialog dialog = new MyDialog(this);
		dialog.setSimpleSelectPicker(array, currentIndex)
				.setTitle("请选择周期")
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						WheelView wv_content = (WheelView) v
								.findViewById(R.id.simpleSelectPicker);
						int index = wv_content.getCurrentItem();

						TextView zqValueTextView = (TextView) findViewById(R.id.zqValueTextView);
						zqValueTextView.setText(String.valueOf(dataArraylist
								.get(index)));

						mMenstrualCycle = dataArraylist.get(index);

					}
				}).create(null).show();
	}

	private void showBeginTimeValue() {
		
		Date date = DateUtilBase.dateFromString(mLastMenstruationDate, DateUtilBase.YEAR_MONTH_DAY);
		
		new MyDialog(this)
				.setTitle("请选择开始时间")
				.setDateTimePicker(date, DateType.YEAR_MONTH_DAY)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {

						// 如果是个数,则显示为"02"的样式
						WheelView wv_year = (WheelView) v
								.findViewById(R.id.year);
						WheelView wv_month = (WheelView) v
								.findViewById(R.id.month);
						WheelView wv_day = (WheelView) v.findViewById(R.id.day);

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String date = (wv_year.getCurrentItem() + MyDialog.START_YEAR)
								+ "-"
								+ decimal.format((wv_month.getCurrentItem() + 1))
								+ "-"
								+ decimal.format((wv_day.getCurrentItem() + 1));

						Date selectDate = DateUtilBase.dateFromString(date,
								DateUtilBase.YEAR_MONTH_DAY);
						long selectTime = selectDate.getTime();
						Date currentDate = DateUtilBase.dateFromString(
								DateUtilBase.stringFromDate(new Date(),
										DateUtilBase.YEAR_MONTH_DAY),
								DateUtilBase.YEAR_MONTH_DAY);
						long currentTime = currentDate.getTime();

						if (selectTime > currentTime) {
							UIHelper.showToast(JqtxMainActivity.this,
									R.string.bbwy_sleep_tip_3);
							return;
						}

						mLastMenstruationDate = date;
						TextView beginTimeValueTextView = (TextView) findViewById(R.id.beginTimeValueTextView);
						beginTimeValueTextView.setText(date);
					}
				}).create(null).show();
	}

	@SuppressLint("InflateParams")
	private void showTxTimeValue() {
		View view = LayoutInflater.from(this).inflate(
				R.layout.tool_yimiao_date_view, null);

		// ------ string wheel
		final WheelView wv_content = (WheelView) view.findViewById(R.id.custom);
		wv_content.setAdapter(new ArrayWheelAdapter<String>(mRemindArray));
		wv_content.setCurrentItem(mAlertBeforeDay-1);

		// ------ 时：分
		int hour = 0;
		int minutes = 0;

		Calendar calendar = Calendar.getInstance();

		Date timeDate = DateUtilBase.dateFromString(mAlertTime, "HH:mm:ss");
		calendar.setTime(timeDate);

		hour = calendar.get(Calendar.HOUR_OF_DAY);
		minutes = calendar.get(Calendar.MINUTE);

		// 时
		final WheelView wv_hour = (WheelView) view.findViewById(R.id.hour);
		wv_hour.setAdapter(new NumericWheelAdapter(0, 23));
		wv_hour.setCyclic(true);// 可循环滚动
		wv_hour.setLabel("时");// 添加文字
		wv_hour.setCurrentItem(hour);// 初始化时显示的数据

		// 分
		final WheelView wv_minutes = (WheelView) view.findViewById(R.id.minute);
		wv_minutes.setAdapter(new NumericWheelAdapter(0, 59));
		wv_minutes.setCyclic(true);
		wv_minutes.setLabel("分");
		wv_minutes.setCurrentItem(minutes);

		// 根据屏幕密度来指定选择器字体的大小
		int textSize = UtilityBase.getTextNumberSize(this);

		wv_content.TEXT_SIZE = textSize;
		wv_hour.TEXT_SIZE = textSize;
		wv_minutes.TEXT_SIZE = textSize;

		MyDialog dialog = new MyDialog(this)
				.setTitle("请选择提醒时间")
				.addView(view)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						int currentItem = wv_content.getCurrentItem();

						String parten = "00";
						DecimalFormat decimal = new DecimalFormat(parten);
						// 设置日期的显示
						String date = mRemindArray[currentItem] + " "
								+ decimal.format((wv_hour.getCurrentItem()))
								+ ":"
								+ decimal.format((wv_minutes.getCurrentItem()));

						TextView txTimeValueTextView = (TextView) findViewById(R.id.txTimeValueTextView);
						txTimeValueTextView.setText(date);

						mAlertTime = decimal.format((wv_hour.getCurrentItem()))
								+ ":"
								+ decimal.format((wv_minutes.getCurrentItem()))
								+ ":" + "00";
						mAlertBeforeDay = (currentItem + 1);
					}
				});

		dialog.create(null).show();
	}

	private void submit() {

		StringBuffer sb = new StringBuffer();
		if (mIsAlert == 1) {
			if (mAlertTypeMaps.size() <= 0) {
				UIHelper.showToast(this, R.string.jqtx_tip_1);
				return;
			}
			
			if (mAlertTypeMaps.size() > 0)
			{
				for (Map.Entry<String, Integer> entry : mAlertTypeMaps.entrySet()) {
					sb.append(entry.getValue());
					sb.append('|');
				}
				sb.deleteCharAt(sb.length() - 1);
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("MenstrualPeriod", mMenstrualPeriod);
			params.put("MenstrualCycle", mMenstrualCycle);
			params.put("LastMenstruationDate", mLastMenstruationDate);

			params.put("IsAlert", mIsAlert);

			if (mIsAlert == 1) {
				params.put("AlertType", sb.toString());
				params.put("AlertBeforeDay", mAlertBeforeDay);
				params.put("AlertTime", mAlertTime);
			}

		} catch (Exception e) {
		}
		map.put("ht", params);

		mTempBeanJqtx = new BeanJqtx();
		mTempBeanJqtx.MenstrualCycle = mMenstrualCycle;
		mTempBeanJqtx.MenstrualPeriod = mMenstrualPeriod;
		mTempBeanJqtx.LastMenstruationDate = mLastMenstruationDate;
		mTempBeanJqtx.IsAlert = mIsAlert;
		
		if(mIsAlert == 1)
		{
			mTempBeanJqtx.AlertType = sb.toString();
			mTempBeanJqtx.AlertBeforeDay = mAlertBeforeDay;
			mTempBeanJqtx.AlertTime = mAlertTime;
		}

		showProgressDialog();
		ApiClient.http_post_main(Setting.getSaveUserMenstruationUrl(), map,
				null, this, REQUEST_FINISH, true);
	}

	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_FINISH)) {
			hideProgressDialog();

			// 更新经期提醒
			String submitData = BeanJqtx.getJsonByBean(mTempBeanJqtx);
			ToolJqtxUtil.getInstance(this).updateJqtx(submitData);

			Intent intent = new Intent(this, JqtxMainResultActivity.class);
			startActivity(intent, true);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_FINISH)) {
			hideProgressDialog();
		}
	}
}
